package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 需求：查询location 表中所有记录
 * SQL: SELECT id,name FROM location
 */

public class TestSelect {
    public static void main(String[] args) throws Exception {

        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取和数据库的连接
        //2.1指定URL,确定要连接哪个数据库
        String url = "jdbc:mysql://localhost:3306/tedu?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
       //2.2指定使用的用户名
        String user="root";
        //2.3指定使用的密码
        String pwd="root";
        //2.4调用DriverManager类的getConnection()方法建立到数据库的连接
        Connection conn= DriverManager.getConnection(url,user,pwd);
        System.out.println("连接成功~~");
        System.out.println("连接成功!获取的连接器对象是: "+conn);
        String sql="SELECT id,name FROM location";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        /**
         * 查询 executeQuery()
         * 返回值为结果集
         */
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println(id+"\t"+name);
        }
        resultSet.close();
        preparedStatement.close();
        conn.close();

    }
}
